package com.example.apione.controller.index;

import com.example.apione.dao.ApiAccesslogDao;
import com.example.apione.dao.ApiInfoDao;
import com.example.apione.entity.ApiAccesslog;
import com.example.apione.model.getApimodel;
import com.example.apione.utils.IPUtils;
import com.example.apione.utils.ResponseResult;
import lombok.Data;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;


/**
 * @author 尘落
 * @date 2023/2/23
 */
@Data
@RestController
public class ListenApi {
    private final ApiInfoDao apiInfoDao;
    private final ApiAccesslogDao apiAccesslogDao;
    private WebClient webClient = WebClient.builder()
            .build();
    @GetMapping(value = "/send")
    public ResponseEntity<Object> listenapi(@RequestParam HashMap<String,String> params, HttpServletRequest request, HttpServletResponse response) {
        String apiname = params.get("apiname");
        String apiurl = "";
        String url = getApimodel.oneapidoc(apiInfoDao, apiname);//拿到实际api的url
        params.remove("apiname");
        String[] keys = params.keySet().toArray(new String[0]);//拿到所有参数数组
        if (keys.length == 0) {//判断参数个数拼成链接
            apiurl = url;
        } else if (keys.length == 1) {
            apiurl = String.format(url + "?%s=%s", keys[0], params.get(keys[0]));
        } else if (keys.length >= 2) {
            apiurl = String.format(url + "?%s=%s&&%s=%s", keys[0], params.get(keys[0]), keys[1], params.get(keys[1]));
        } else {
            apiurl = String.format(url + "?%s=%s&&%s=%s&&%s=%s", keys[0], params.get(keys[0]), keys[1], params.get(keys[1]),
                    keys[2], params.get(keys[2]));
        }
        HttpHeaders headers = new HttpHeaders();;
        try {
            System.out.println(apiurl);
            //发送请求
            Mono<ClientResponse> mono = webClient
                    .get() // GET 请求
                    .uri(apiurl)  // 请求路径
                    .exchange();
            ClientResponse resource = mono.block();
            String type = String.valueOf(resource.headers().contentType().get());//拿到contentType类型
            //进行contentType类型判断
            if (type.equals("application/json")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                Resource data = resource.bodyToMono(Resource.class).block();
                return new ResponseEntity<Object>(data, headers, HttpStatus.OK);
            } else if (type.equals("image/png") || type.equals("image/gif") || type.equals("image/jpeg")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE);
                Resource data = resource.bodyToMono(Resource.class).block();
                return new ResponseEntity<Object>(data, headers, HttpStatus.OK);
            } else {
                headers.add(HttpHeaders.CONTENT_TYPE, "text/html;charset=UTF-8");
                Resource data = resource.bodyToMono(Resource.class).block();
                return new ResponseEntity<Object>(data, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            String data = "{"+"\"code\": 666," + "\"msg\": \"参数错误\"," + " \"data\":请检查！"+"}";
            return new ResponseEntity<Object>(data, headers, HttpStatus.OK);
        } finally {
            addAcceess(apiAccesslogDao, request, apiurl);
        }


    }
    //增加Accesslog数据表数据
    public static void addAcceess(ApiAccesslogDao apiAccesslogDao,HttpServletRequest request,String apiurl){
        LocalDateTime createtime =LocalDateTime.now();
        String user_agent=request.getHeader("user-agent");
        String method = request.getMethod();
        String protocol=request.getProtocol();
        long createtime1=createtime.toEpochSecond(ZoneOffset.ofHours(8));
        String ip= IPUtils.getIpAddr(request);
//        String ip2 =request.getRemoteAddr();
//        System.out.println(createtime1);
//        System.out.println(user_agent);
//        System.out.println(method);
//        System.out.println(ip2);
        ApiAccesslog apiAccesslog =new ApiAccesslog();
        apiAccesslog.setIp(ip);
        apiAccesslog.setHost(apiurl);
        apiAccesslog.setUserAgent(user_agent);
        apiAccesslog.setMethod(method);
        apiAccesslog.setProtocol(protocol);
        apiAccesslog.setCreateTime(createtime1);
        apiAccesslogDao.insert(apiAccesslog);
    }

}
